import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

/**
 * 折线图组件
 * @description 基于 ECharts 的折线图封装
 * 
 * @example
 * ```tsx
 * <LineChart
 *   title="销售趋势"
 *   data={{
 *     xAxis: ['Mon', 'Tue', 'Wed'],
 *     series: [100, 200, 300]
 *   }}
 *   loading={loading}
 *   height={400}
 * />
 * ```
 * 
 * @param data - 图表数据
 * @param title - 图表标题
 * @param loading - 加载状态
 * @param height - 图表高度
 */
interface LineChartProps {
  data: {
    xAxis: string[]
    series: number[]
  }
  title?: string
  loading?: boolean
  height?: number
  style?: React.CSSProperties
}

const LineChart: React.FC<LineChartProps> = ({
  data,
  title,
  loading,
  height = 400,
  style
}) => {
  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstance = useRef<echarts.ECharts>()

  useEffect(() => {
    if (!chartRef.current) return

    chartInstance.current = echarts.init(chartRef.current)

    const option: EChartsOption = {
      title: title ? { text: title } : undefined,
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.xAxis
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: data.series,
        type: 'line',
        smooth: true
      }],
      loading
    }

    chartInstance.current.setOption(option)

    return () => {
      chartInstance.current?.dispose()
    }
  }, [data, title, loading])

  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize()
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  return (
    <div 
      ref={chartRef} 
      style={{ height, ...style }}
    />
  )
}

export default LineChart 